package com.dmall.graph.dfs;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 非递归方式实现图的深度优先遍历
 */
public class GraphDFSNR {

    private Graph G;
    private boolean[] visited;

    private ArrayList<Integer> pre = new ArrayList<>();

    public GraphDFSNR(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];

        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                dfs(i);
            }
        }
    }

    private void dfs(int v) {
        visited[v] = true;
        Stack<Integer> stack = new Stack<>();
        stack.push(v);

        while (!stack.isEmpty()) {
            Integer x = stack.pop();
            pre.add(x);
            for (Integer w : G.adj(x)) {
                if (!visited[w]) {
                    visited[w] = true;
                    stack.push(w);
                }
            }
        }
    }

    public Iterable<Integer> pre() {
        return pre;
    }

    public static void main(String[] args) {
        String filePath = GraphDFSNR.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        GraphDFSNR graphDFS = new GraphDFSNR(graph);
        System.out.println(graphDFS.pre());
    }
}
